<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>复杂判断的更优雅写法 | 孙志豪的博客</title><meta name="author" content="孙志豪"><meta name="copyright" content="孙志豪"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JavaScript 复杂判断的更优雅写法前提我们编写js代码时经常遇到复杂逻辑判断的情况，通常大家可以用if&#x2F;else或者switch来实现多个条件判断，但这样会有个问题，随着逻辑复杂度的增加，代码中的if&#x2F;else&#x2F;switch会变得越来越臃肿，越来越看不懂，那么如何更优雅的写判断逻辑，本文带你试一下。 举个例子先看一段代码 123456789101112131">
<meta property="og:type" content="article">
<meta property="og:title" content="复杂判断的更优雅写法">
<meta property="og:url" content="https://szhihao.gitee.io/2022/10/11/06-%E6%A0%B8%E5%BF%83js%EF%BC%88%E9%AA%9A%E5%8C%85%E6%8A%80%E5%B7%A7%E7%AF%87%EF%BC%89/JavaScript%20%E5%A4%8D%E6%9D%82%E5%88%A4%E6%96%AD%E7%9A%84%E6%9B%B4%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95/index.html">
<meta property="og:site_name" content="孙志豪的博客">
<meta property="og:description" content="JavaScript 复杂判断的更优雅写法前提我们编写js代码时经常遇到复杂逻辑判断的情况，通常大家可以用if&#x2F;else或者switch来实现多个条件判断，但这样会有个问题，随着逻辑复杂度的增加，代码中的if&#x2F;else&#x2F;switch会变得越来越臃肿，越来越看不懂，那么如何更优雅的写判断逻辑，本文带你试一下。 举个例子先看一段代码 123456789101112131">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://szhihao.gitee.io/img/%E5%A4%A9%E7%A9%BA.jpeg">
<meta property="article:published_time" content="2022-10-11T12:01:36.000Z">
<meta property="article:modified_time" content="2022-10-11T09:29:45.703Z">
<meta property="article:author" content="孙志豪">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://szhihao.gitee.io/img/%E5%A4%A9%E7%A9%BA.jpeg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://szhihao.gitee.io/2022/10/11/06-%E6%A0%B8%E5%BF%83js%EF%BC%88%E9%AA%9A%E5%8C%85%E6%8A%80%E5%B7%A7%E7%AF%87%EF%BC%89/JavaScript%20%E5%A4%8D%E6%9D%82%E5%88%A4%E6%96%AD%E7%9A%84%E6%9B%B4%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '复杂判断的更优雅写法',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-11 17:29:45'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">44</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">15</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/%E5%A4%A9%E7%A9%BA.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">孙志豪的博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">复杂判断的更优雅写法</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2022-10-11T09:29:45.703Z" title="Updated 2022-10-11 17:29:45">2022-10-11</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%A0%B8%E5%BF%83js%EF%BC%88%E9%AA%9A%E5%8C%85%E6%8A%80%E5%B7%A7%E7%AF%87%EF%BC%89/">核心js（骚包技巧篇）</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="复杂判断的更优雅写法"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><hr>
<h1 id="JavaScript-复杂判断的更优雅写法"><a href="#JavaScript-复杂判断的更优雅写法" class="headerlink" title="JavaScript 复杂判断的更优雅写法"></a>JavaScript 复杂判断的更优雅写法</h1><h3 id="前提"><a href="#前提" class="headerlink" title="前提"></a>前提</h3><p>我们编写js代码时经常遇到复杂逻辑判断的情况，通常大家可以用if&#x2F;else或者switch来实现多个条件判断，但这样会有个问题，随着逻辑复杂度的增加，代码中的if&#x2F;else&#x2F;switch会变得越来越臃肿，越来越看不懂，那么如何更优雅的写判断逻辑，本文带你试一下。</p>
<h3 id="举个例子"><a href="#举个例子" class="headerlink" title="举个例子"></a>举个例子</h3><p>先看一段代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">number</span>&#125; status 活动状态：1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">if</span>(status == <span class="number">1</span>)&#123;</span><br><span class="line">    <span class="title function_">sendLog</span>(<span class="string">&#x27;processing&#x27;</span>)</span><br><span class="line">    <span class="title function_">jumpTo</span>(<span class="string">&#x27;IndexPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">2</span>)&#123;</span><br><span class="line">    <span class="title function_">sendLog</span>(<span class="string">&#x27;fail&#x27;</span>)</span><br><span class="line">    <span class="title function_">jumpTo</span>(<span class="string">&#x27;FailPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">3</span>)&#123;</span><br><span class="line">    <span class="title function_">sendLog</span>(<span class="string">&#x27;fail&#x27;</span>)</span><br><span class="line">    <span class="title function_">jumpTo</span>(<span class="string">&#x27;FailPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">4</span>)&#123;</span><br><span class="line">    <span class="title function_">sendLog</span>(<span class="string">&#x27;success&#x27;</span>)</span><br><span class="line">    <span class="title function_">jumpTo</span>(<span class="string">&#x27;SuccessPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">5</span>)&#123;</span><br><span class="line">    <span class="title function_">sendLog</span>(<span class="string">&#x27;cancel&#x27;</span>)</span><br><span class="line">    <span class="title function_">jumpTo</span>(<span class="string">&#x27;CancelPage&#x27;</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="title function_">sendLog</span>(<span class="string">&#x27;other&#x27;</span>)</span><br><span class="line">    <span class="title function_">jumpTo</span>(<span class="string">&#x27;Index&#x27;</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>通过代码可以看到这个按钮的点击逻辑：根据不同活动状态做两件事情，发送日志埋点和跳转到对应页面，大家可以很轻易的提出这段代码的改写方案，switch出场：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">number</span>&#125; status 活动状态：1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">switch</span> (status)&#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">      <span class="title function_">sendLog</span>(<span class="string">&#x27;processing&#x27;</span>)</span><br><span class="line">      <span class="title function_">jumpTo</span>(<span class="string">&#x27;IndexPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">      <span class="title function_">sendLog</span>(<span class="string">&#x27;fail&#x27;</span>)</span><br><span class="line">      <span class="title function_">jumpTo</span>(<span class="string">&#x27;FailPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span>  </span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">      <span class="title function_">sendLog</span>(<span class="string">&#x27;success&#x27;</span>)</span><br><span class="line">      <span class="title function_">jumpTo</span>(<span class="string">&#x27;SuccessPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">      <span class="title function_">sendLog</span>(<span class="string">&#x27;cancel&#x27;</span>)</span><br><span class="line">      <span class="title function_">jumpTo</span>(<span class="string">&#x27;CancelPage&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">      <span class="title function_">sendLog</span>(<span class="string">&#x27;other&#x27;</span>)</span><br><span class="line">      <span class="title function_">jumpTo</span>(<span class="string">&#x27;Index&#x27;</span>)</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>嗯，这样看起来比if&#x2F;else清晰多了，细心的同学也发现了小技巧，case 2和case 3逻辑一样的时候，可以省去执行语句和break，则case 2的情况自动执行case 3的逻辑。</p>
<p>这时有同学会说，还有更简单的写法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> actions = &#123;</span><br><span class="line">  <span class="string">&#x27;1&#x27;</span>: [<span class="string">&#x27;processing&#x27;</span>,<span class="string">&#x27;IndexPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;2&#x27;</span>: [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;3&#x27;</span>: [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;4&#x27;</span>: [<span class="string">&#x27;success&#x27;</span>,<span class="string">&#x27;SuccessPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;5&#x27;</span>: [<span class="string">&#x27;cancel&#x27;</span>,<span class="string">&#x27;CancelPage&#x27;</span>],</span><br><span class="line">  <span class="string">&#x27;default&#x27;</span>: [<span class="string">&#x27;other&#x27;</span>,<span class="string">&#x27;Index&#x27;</span>],</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">number</span>&#125; status 活动状态：1开团进行中 2开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions[status] || actions[<span class="string">&#x27;default&#x27;</span>],</span><br><span class="line">      logName = action[<span class="number">0</span>],</span><br><span class="line">      pageName = action[<span class="number">1</span>]</span><br><span class="line">  <span class="title function_">sendLog</span>(logName)</span><br><span class="line">  <span class="title function_">jumpTo</span>(pageName)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>上面代码确实看起来更清爽了，这种方法的聪明之处在于：将判断条件作为对象的属性名，将处理逻辑作为对象的属性值，在按钮点击的时候，通过对象属性查找的方式来进行逻辑判断，这种写法特别适合一元条件判断的情况。</p>
<p>是不是还有其他写法呢？有的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">  [<span class="number">1</span>, [<span class="string">&#x27;processing&#x27;</span>,<span class="string">&#x27;IndexPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">2</span>, [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">3</span>, [<span class="string">&#x27;fail&#x27;</span>,<span class="string">&#x27;FailPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">4</span>, [<span class="string">&#x27;success&#x27;</span>,<span class="string">&#x27;SuccessPage&#x27;</span>]],</span><br><span class="line">  [<span class="number">5</span>, [<span class="string">&#x27;cancel&#x27;</span>,<span class="string">&#x27;CancelPage&#x27;</span>]],</span><br><span class="line">  [<span class="string">&#x27;default&#x27;</span>, [<span class="string">&#x27;other&#x27;</span>,<span class="string">&#x27;Index&#x27;</span>]]</span><br><span class="line">])</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">number</span>&#125; status 活动状态：1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions.<span class="title function_">get</span>(status) || actions.<span class="title function_">get</span>(<span class="string">&#x27;default&#x27;</span>)</span><br><span class="line">  <span class="title function_">sendLog</span>(action[<span class="number">0</span>])</span><br><span class="line">  <span class="title function_">jumpTo</span>(action[<span class="number">1</span>])</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这样写用到了es6里的Map对象，是不是更爽了？Map对象和Object对象有什么区别呢？</p>
<ol>
<li>一个对象通常都有自己的原型，所以一个对象总有一个”prototype”键。</li>
<li>一个对象的键只能是字符串或者Symbols，但一个Map的键可以是任意值。</li>
<li>你可以通过size属性很容易地得到一个Map的键值对个数，而对象的键值对个数只能手动确认。</li>
</ol>
<p>我们需要把问题升级一下，以前按钮点击时候只需要判断status，现在还需要判断用户的身份：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">number</span>&#125; status 活动状态：1开团进行中 2开团失败 3 开团成功 4 商品售罄 5 有库存未开团</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">string</span>&#125; identity 身份标识：guest客态 master主态</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">status,identity</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">if</span>(identity == <span class="string">&#x27;guest&#x27;</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(status == <span class="number">1</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">2</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">3</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">4</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">5</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(identity == <span class="string">&#x27;master&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span>(status == <span class="number">1</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">2</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">3</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">4</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(status == <span class="number">5</span>)&#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>原谅我不写每个判断里的具体逻辑了，因为代码太冗长了。</p>
<p>原谅我又用了if&#x2F;else，因为我看到很多人依然在用if&#x2F;else写这种大段的逻辑判断。</p>
<p>从上面的例子我们可以看到，当你的逻辑升级为二元判断时，你的判断量会加倍，你的代码量也会加倍，这时怎么写更清爽呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">  [<span class="string">&#x27;guest_1&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_2&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_3&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_4&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;guest_5&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_1&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_2&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_3&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_4&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;master_5&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [<span class="string">&#x27;default&#x27;</span>, <span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">])</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 按钮点击事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">string</span>&#125; identity 身份标识：guest客态 master主态</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &#123;<span class="type">number</span>&#125; status 活动状态：1 开团进行中 2 开团失败 3 开团成功 4 商品售罄 5 有库存未开团</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">identity,status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions.<span class="title function_">get</span>(<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>) || actions.<span class="title function_">get</span>(<span class="string">&#x27;default&#x27;</span>)</span><br><span class="line">  action.<span class="title function_">call</span>(<span class="variable language_">this</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>上述代码核心逻辑是：把两个条件拼接成字符串，并通过以条件拼接字符串作为键，以处理函数作为值的Map对象进行查找并执行，这种写法在多元条件判断时候尤其好用。</p>
<p>当然上述代码如果用Object对象来实现也是类似的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> actions = &#123;</span><br><span class="line">  <span class="string">&#x27;guest_1&#x27;</span>:<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;,</span><br><span class="line">  <span class="string">&#x27;guest_2&#x27;</span>:<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;,</span><br><span class="line">  <span class="comment">//....</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">identity,status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = actions[<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>] || actions[<span class="string">&#x27;default&#x27;</span>]</span><br><span class="line">  action.<span class="title function_">call</span>(<span class="variable language_">this</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>如果有些同学觉得把查询条件拼成字符串有点别扭，那还有一种方案，就是用Map对象，以Object对象作为key：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">1</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">2</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/*do sth*/</span>&#125;],</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">])</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">identity,status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...actions].<span class="title function_">filter</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.<span class="property">identity</span> == identity &amp;&amp; key.<span class="property">status</span> == status))</span><br><span class="line">  action.<span class="title function_">forEach</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.<span class="title function_">call</span>(<span class="variable language_">this</span>))</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>是不是又高级了一点点？</p>
<p>这里也看出来Map与Object的区别，Map可以用任何类型的数据作为key。</p>
<p>我们现在再将难度升级一点点，假如guest情况下，status1-4的处理逻辑都一样怎么办，最差的情况是这样：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> actions = <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">1</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">2</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">3</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">4</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionA */</span>&#125;],</span><br><span class="line">  [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">5</span>&#125;,<span class="function">()=&gt;</span>&#123;<span class="comment">/* functionB */</span>&#125;],</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">])</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>好一点的写法是将处理逻辑函数进行缓存：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">actions</span> = (<span class="params"></span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionA</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionB</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">1</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">2</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">3</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">4</span>&#125;,functionA],</span><br><span class="line">    [&#123;<span class="attr">identity</span>:<span class="string">&#x27;guest&#x27;</span>,<span class="attr">status</span>:<span class="number">5</span>&#125;,functionB],</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  ])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">identity,status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...<span class="title function_">actions</span>()].<span class="title function_">filter</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.<span class="property">identity</span> == identity &amp;&amp; key.<span class="property">status</span> == status))</span><br><span class="line">  action.<span class="title function_">forEach</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.<span class="title function_">call</span>(<span class="variable language_">this</span>))</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这样写已经能满足日常需求了，但认真一点讲，上面重写了4次functionA还是有点不爽，假如判断条件变得特别复杂，比如identity有3种状态，status有10种状态，那你需要定义30条处理逻辑，而往往这些逻辑里面很多都是相同的，这似乎也是笔者不想接受的，那可以这样实现:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">actions</span> = (<span class="params"></span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionA</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionB</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">    [<span class="regexp">/^guest_[1-4]$/</span>,functionA],</span><br><span class="line">    [<span class="regexp">/^guest_5$/</span>,functionB],</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  ])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">identity,status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...<span class="title function_">actions</span>()].<span class="title function_">filter</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.<span class="title function_">test</span>(<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>)))</span><br><span class="line">  action.<span class="title function_">forEach</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.<span class="title function_">call</span>(<span class="variable language_">this</span>))</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这里Map的优势更加凸显，可以用正则类型作为key了，这样就有了无限可能，假如需求变成，凡是guest情况都要发送一个日志埋点，不同status情况也需要单独的逻辑处理，那我们可以这样写:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">actions</span> = (<span class="params"></span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionA</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionB</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*do sth*/</span>&#125;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">functionC</span> = (<span class="params"></span>)=&gt;&#123;<span class="comment">/*send log*/</span>&#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Map</span>([</span><br><span class="line">    [<span class="regexp">/^guest_[1-4]$/</span>,functionA],</span><br><span class="line">    [<span class="regexp">/^guest_5$/</span>,functionB],</span><br><span class="line">    [<span class="regexp">/^guest_.*$/</span>,functionC],</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">  ])</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">onButtonClick</span> = (<span class="params">identity,status</span>)=&gt;&#123;</span><br><span class="line">  <span class="keyword">let</span> action = [...<span class="title function_">actions</span>()].<span class="title function_">filter</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>(key.<span class="title function_">test</span>(<span class="string">`<span class="subst">$&#123;identity&#125;</span>_<span class="subst">$&#123;status&#125;</span>`</span>)))</span><br><span class="line">  action.<span class="title function_">forEach</span>(<span class="function">(<span class="params">[key,value]</span>)=&gt;</span>value.<span class="title function_">call</span>(<span class="variable language_">this</span>))</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>也就是说利用数组循环的特性，符合正则条件的逻辑都会被执行，那就可以同时执行公共逻辑和单独逻辑，因为正则的存在，你可以打开想象力解锁更多的玩法，本文就不赘述了。</p>
<h3 id="本文已经教你了8种逻辑判断写法，包括："><a href="#本文已经教你了8种逻辑判断写法，包括：" class="headerlink" title="本文已经教你了8种逻辑判断写法，包括："></a>本文已经教你了8种逻辑判断写法，包括：</h3><ol>
<li>if&#x2F;else</li>
<li>switch</li>
<li>一元判断时：存到Object里</li>
<li>一元判断时：存到Map里</li>
<li>多元判断时：将condition拼接成字符串存到Object里</li>
<li>多元判断时：将condition拼接成字符串存到Map里</li>
<li>多元判断时：将condition存为Object存到Map里</li>
<li>多元判断时：将condition写作正则存到Map里</li>
</ol>
<p>至此，本文也将告一段落，愿你未来的人生里，不只是有if&#x2F;else&#x2F;switch。</p>
<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://szhihao.gitee.io">孙志豪</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://szhihao.gitee.io/2022/10/11/06-%E6%A0%B8%E5%BF%83js%EF%BC%88%E9%AA%9A%E5%8C%85%E6%8A%80%E5%B7%A7%E7%AF%87%EF%BC%89/JavaScript%20%E5%A4%8D%E6%9D%82%E5%88%A4%E6%96%AD%E7%9A%84%E6%9B%B4%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95/">https://szhihao.gitee.io/2022/10/11/06-%E6%A0%B8%E5%BF%83js%EF%BC%88%E9%AA%9A%E5%8C%85%E6%8A%80%E5%B7%A7%E7%AF%87%EF%BC%89/JavaScript%20%E5%A4%8D%E6%9D%82%E5%88%A4%E6%96%AD%E7%9A%84%E6%9B%B4%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="/img/%E5%A4%A9%E7%A9%BA.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/10/11/09-%E6%A0%B8%E5%BF%83js%EF%BC%88%E5%8E%9F%E7%90%86%E7%AF%87%EF%BC%89/js%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98%E6%A2%B3%E7%90%86/"><img class="prev-cover" src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">JS 问题梳理</div></div></a></div><div class="next-post pull-right"><a href="/2022/10/11/13-%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91%E8%B7%AF%E7%BA%BF/%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91%E8%B7%AF%E7%BA%BF/"><img class="next-cover" src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">前端开发路线</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">孙志豪</div><div class="author-info__description">吾日三省吾身：为人谋而不忠乎？与朋友交而不信乎？传不习乎？</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">44</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">15</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/szhihao/szhihao"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/szhihao/szhihao" target="_blank" title="Gitee"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_54753561" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="mailto:zhihaomail@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-%E5%A4%8D%E6%9D%82%E5%88%A4%E6%96%AD%E7%9A%84%E6%9B%B4%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95"><span class="toc-number">1.</span> <span class="toc-text">JavaScript 复杂判断的更优雅写法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E6%8F%90"><span class="toc-number">1.0.1.</span> <span class="toc-text">前提</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%B8%AA%E4%BE%8B%E5%AD%90"><span class="toc-number">1.0.2.</span> <span class="toc-text">举个例子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%AC%E6%96%87%E5%B7%B2%E7%BB%8F%E6%95%99%E4%BD%A0%E4%BA%868%E7%A7%8D%E9%80%BB%E8%BE%91%E5%88%A4%E6%96%AD%E5%86%99%E6%B3%95%EF%BC%8C%E5%8C%85%E6%8B%AC%EF%BC%9A"><span class="toc-number">1.0.3.</span> <span class="toc-text">本文已经教你了8种逻辑判断写法，包括：</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/10/12/04-%E5%89%8D%E7%AB%AF%EF%BC%88%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87%EF%BC%89/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87/" title="性能优化面试题"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="性能优化面试题"/></a><div class="content"><a class="title" href="/2022/10/12/04-%E5%89%8D%E7%AB%AF%EF%BC%88%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87%EF%BC%89/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87/" title="性能优化面试题">性能优化面试题</a><time datetime="2022-10-12T12:01:36.000Z" title="Created 2022-10-12 20:01:36">2022-10-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS字符串方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS字符串方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS字符串方法">JS字符串方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS对象方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS对象方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS对象方法">JS对象方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E6%9F%A5%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS数组方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS数组方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E6%9F%A5%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS数组方法">JS数组方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%BC%80%E5%8F%91%E5%B0%81%E8%A3%85%E5%87%BD%E6%95%B0/" title="开发封装函数"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="开发封装函数"/></a><div class="content"><a class="title" href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%BC%80%E5%8F%91%E5%B0%81%E8%A3%85%E5%87%BD%E6%95%B0/" title="开发封装函数">开发封装函数</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By 孙志豪</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Search</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  Loading the Database</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>